package com.app.backend.common.utils;

import com.app.backend.common.aware.SpringContextAware;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jet Zheng
 */
@Slf4j
public class JsonUtils {

    public static String toJson(Object object) {
        try {
            return getObjectMapper().writeValueAsString(object);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return StringUtils.EMPTY;
        }
    }

    private static ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = SpringContextAware.getBean(ObjectMapper.class);
        if (objectMapper == null) {
            log.info("cannot find the object mapper");
        }
        return objectMapper;
    }

    public static <T> T toObject(String json, Class<T> classOfT) {
        try {
            if (StringUtils.isBlank(json) || StringUtils.equalsIgnoreCase("null", json)) {
                return null;
            }
            return getObjectMapper().readValue(json, classOfT);
        } catch (Exception e) {
            log.error("Json -> Object 格式化错误:{},错误原因:{}", json, e.getMessage());
            return null;
        }
    }

    public static <T> List<T> toList(String json, Class<T> classOfT) {
        try {
            if (StringUtils.isBlank(json) || StringUtils.equalsIgnoreCase("null", json)) {
                return Lists.newArrayList();
            }
            ObjectMapper objectMapper = getObjectMapper();
            JavaType javaType = getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, classOfT);
            return objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            log.error("Json -> List 格式化错误 , {}", json);
            return Lists.newArrayList();
        }
    }

    public static boolean isJsonObject(String json) {
        try {
            JsonNode jsonNode = getObjectMapper().readTree(json);
            return jsonNode.isObject();
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isJsonArray(String json) {
        try {
            return getObjectMapper().readTree(json).isArray();
        } catch (Exception e) {
            return false;
        }
    }

}
